﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using StoreManagement.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace StoreManagement.ViewModel
{
    public class LoginViewModel : ViewModelBase
    {
        public AppData AppData { get; private set; } = AppData.Instance;
        private UserInfo user = new UserInfo() {Name="admin",Password="0" };
        public UserInfo User
        {
            get { return user; }
            set { user = value; RaisePropertyChanged(); }
        }

        public RelayCommand<Window> LoginCommand
        {
            get
            {
                var command = new RelayCommand<Window>((window) =>
                {
                    if(string.IsNullOrEmpty(User.Name) == true || string.IsNullOrEmpty(User.Password) == true)
                    {
                        return;
                    }

                    UserInfoService userInfoService = new UserInfoService();
                    var users = userInfoService.Select();
                    var item = users.FirstOrDefault(t=>t.Name == user.Name && t.Password == User.Password);
                    if(item != null)
                    {
                        this.AppData.User = item;
                        MainWindow mainWindow = new MainWindow();
                        mainWindow.Show();
                        window.Close();
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码错误");
                    }
                });
                return command;
            }
        }
    }
}
